import { http } from '@/library/http'

export default {
  namespaced: true,
  state: {
    list: []
  },
  getters: {
    list (state) {
      if (state.list.length === 0) {
        let data = KE.localStorage.getJson('area')
        if (data) {
          state.list = data
        }
      }
      return state.list
    },
    province (state, getters) {
      return getters.list.filter((item) => item.level === 1)
    },
    city (state, getters) {
      return getters.list.filter((item) => item.level === 2)
    },
    country (state, getters) {
      return getters.list.filter((item) => item.level === 3)
    }
  },
  mutations: {
    saveArea (state, data) {
      KE.localStorage.setJson('area', data)
      state.list = data
    }
  },
  actions: {
    init ({ getters, commit }) {
      return new Promise((resolve, reject) => {
        if (getters.list.length === 0) {
          http.get('admin/area', { pid: -1 })
            .then(result => {
              commit('saveArea', result.list)
              resolve()
            })
            .catch((err) => {
              reject(err)
            })
        } else {
          resolve()
        }
      })
    }
  }
}
